package com.supermap.qdsearch.handler;

import android.content.Context;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

import com.supermap.qdsearch.utils.TimeUtils;

import java.io.File;
import java.io.PrintWriter;
import java.util.Date;

/**
 * Created by XueQing Wang on 2018/6/22.
 */
public class CrashHandler implements Thread.UncaughtExceptionHandler {

    private static final String TAG = "CrashHandler";

    private static CrashHandler instance;
    private Thread.UncaughtExceptionHandler defaultUncaughtExceptionHandler;

    private Context context;

    private CrashHandler() {
    }

    public static CrashHandler getInstance(){
        if(instance==null){
            instance = new CrashHandler();
        }
        return instance;
    }


    public void init(Context context){
        defaultUncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(this);
        this.context = context;
    }

    @Override
    public void uncaughtException(Thread t, Throwable ex) {

        if(defaultUncaughtExceptionHandler!=null&&!handleException(ex)){
            defaultUncaughtExceptionHandler.uncaughtException(t,ex);
        }else{
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                Log.e(TAG, "error : ", e);
            }
            //退出程序
            android.os.Process.killProcess(android.os.Process.myPid());
            System.exit(1);
        }
    }

    private boolean handleException(Throwable ex) {
        if (ex == null) {
            return false;
        }

        ex.printStackTrace();

        saveExceptionToFile(ex);
        saveExceptionToServer(ex);
        new Thread() {
            @Override
            public void run() {
                Looper.prepare();
                Toast.makeText(context, "很抱歉,程序出现异常,即将退出...", Toast.LENGTH_SHORT).show();
                Looper.loop();
            }
        }.start();

        return true;
    }

    /**
     * 将异常信息保存到文件中
     * @param ex
     * @throws Exception
     */
    public void saveExceptionToFile(Throwable ex){
        try{
            File file = new File(context.getExternalCacheDir(), TimeUtils.date2String(new Date()) + ".txt");
            if(!file.exists()){
                file.createNewFile();
            }

            PrintWriter printWriter = new PrintWriter(file);
            printWriter.print(ex.getMessage());
            printWriter.close();
        }catch (Exception e){

        }

    }

    /**
     * 将异常信息保存到服务端
     * @param ex
     * @throws Exception
     */
    public void saveExceptionToServer(Throwable ex){

    }
}
